package com.tanhua.management.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.LogMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.Log;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.management.enums.AgeRangeEnum;
import com.tanhua.management.enums.AreaEnum;



import com.tanhua.management.vo.AnalysisDistributionVo;
import com.tanhua.management.vo.AnalysisSummaryVo;
import com.tanhua.management.vo.AnalysisUsersVo;
import com.tanhua.management.vo.DataPointVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AnalysisService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogMapper logMapper;

    //注册用户发布，行业top、年龄、性别、地区
    public AnalysisDistributionVo queryUserDistribution(Long sd, Long ed) {
        AnalysisDistributionVo analysisDistributionVo = new AnalysisDistributionVo();
        /*DateTime start = DateUtil.parse(sd);
        DateTime end = DateUtil.parse(ed);*/
        Date date = DateUtil.beginOfDay(new Date(sd));
        Date date1 =new Date(ed);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start = dateFormat.format(date);
        String end = dateFormat.format(date1);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("Created", start).le("Created", end);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);

        //职业
        ArrayList<DataPointVo> industryDistribution = new ArrayList<>();
        Integer fuWu = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("服务")).collect(Collectors.toList()).size();
        Integer zhiZao = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("制造")).collect(Collectors.toList()).size();
        Integer diChan = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("地产")).collect(Collectors.toList()).size();
        Integer jiaoYu = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("教育")).collect(Collectors.toList()).size();
        Integer zhuSu = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("住宿")).collect(Collectors.toList()).size();
        Integer canYin = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("餐饮")).collect(Collectors.toList()).size();
        /*Integer yuye = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("渔业")).collect(Collectors.toList()).size();
        Integer nongye = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("农业")).collect(Collectors.toList()).size();
        Integer linye = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("林业")).collect(Collectors.toList()).size();
        Integer gongye = userInfos.stream().filter(userInfo -> userInfo.getIndustry().equals("工业")).collect(Collectors.toList()).size();*/
        industryDistribution.add(new DataPointVo("服务", fuWu));
        industryDistribution.add(new DataPointVo("制造", zhiZao));
        industryDistribution.add(new DataPointVo("地产", diChan));
        industryDistribution.add(new DataPointVo("教育", jiaoYu));
        industryDistribution.add(new DataPointVo("住宿", zhuSu));
        industryDistribution.add(new DataPointVo("餐饮", canYin));
        /*industryDistribution.add(new DataPointVo("渔业", yuye ));
        industryDistribution.add(new DataPointVo("农业", nongye));
        industryDistribution.add(new DataPointVo("林业", linye));
        industryDistribution.add(new DataPointVo("工业", gongye));*/

        //年龄
        ArrayList<DataPointVo> ageDistribution = new ArrayList<>();
        Integer age1 = userInfos.stream().filter(userInfo -> userInfo.getAge() >= 0 && userInfo.getAge() < 20).collect(Collectors.toList()).size();
        Integer age2 = userInfos.stream().filter(userInfo -> userInfo.getAge() >= 20 && userInfo.getAge() < 30).collect(Collectors.toList()).size();
        Integer age3 = userInfos.stream().filter(userInfo -> userInfo.getAge() >= 30 && userInfo.getAge() < 40).collect(Collectors.toList()).size();
        Integer age4 = userInfos.stream().filter(userInfo -> userInfo.getAge() >= 40 && userInfo.getAge() < 50).collect(Collectors.toList()).size();
        Integer age5 = userInfos.stream().filter(userInfo -> userInfo.getAge() >= 50 && userInfo.getAge() < 200).collect(Collectors.toList()).size();
        ageDistribution.add(new DataPointVo(AgeRangeEnum.UNDER_TWENTY.getDesc(), age1));
        ageDistribution.add(new DataPointVo(AgeRangeEnum.TWENTY.getDesc(), age2));
        ageDistribution.add(new DataPointVo(AgeRangeEnum.THIRTY.getDesc(), age3));
        ageDistribution.add(new DataPointVo(AgeRangeEnum.FORTY.getDesc(), age4));
        ageDistribution.add(new DataPointVo(AgeRangeEnum.OVER_FIFTY.getDesc(), age5));

        //性别
        ArrayList<DataPointVo> genderDistribution = new ArrayList<>();

        Integer man = userInfos.stream().filter(userInfo -> userInfo.getSex().equals(SexEnum.MAN)).collect(Collectors.toList()).size();
        Integer woman = userInfos.stream().filter(userInfo -> userInfo.getSex().equals(SexEnum.WOMAN)).collect(Collectors.toList()).size();
        genderDistribution.add(new DataPointVo("男性用户", man));
        genderDistribution.add(new DataPointVo("女性用户", woman));

        //地区
        ArrayList<DataPointVo> localDistribution = new ArrayList<>();
        localDistribution.add(new DataPointVo(AreaEnum.HUBEI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HUBEI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HUNAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HUNAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HENAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HENAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.SHANXI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.SHANXI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HEBEI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HEBEI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.BEIJING.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.BEIJING.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.TIANJIN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.TIANJIN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.NEIMENGGU.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.NEIMENGGU.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.ZHEJIANG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.ZHEJIANG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.ANHUI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.ANHUI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.SHANGHAI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.SHANGHAI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.JIANGXI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.JIANGXI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.SHANDONG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.SHANDONG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.JIANGSU.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.JIANGSU.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.FUJIAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.FUJIAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.TAIWAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.TAIWAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.GUANGXI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.GUANGXI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.GUANGDONG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.GUANGDONG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HAINAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HAINAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HONGKONG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HONGKONG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.MACAO.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.MACAO.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.QINGHAI.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.QINGHAI.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.NINGXIA.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.NINGXIA.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.SHANXI2.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.SHANXI2.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.GANSU.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.GANSU.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.XINJIANG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.XINJIANG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.JILIN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.JILIN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.HEILONGJIANG.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.HEILONGJIANG.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.LIAONING.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.LIAONING.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.GUIZHOU.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.GUIZHOU.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.YUNNAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.YUNNAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.CHONGQING.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.CHONGQING.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.SICHUAN.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.SICHUAN.getProvince());
        }).collect(Collectors.toList()).size()));
        localDistribution.add(new DataPointVo(AreaEnum.TIBET.getProvince(), userInfos.stream().filter(userInfo -> {
            String[] city = userInfo.getCity().split("-");
            return city[0].startsWith(AreaEnum.TIBET.getProvince());
        }).collect(Collectors.toList()).size()));


        //地区
        List<DataPointVo> localTotal = new ArrayList<>();
        localTotal.add(new DataPointVo("华中地区", localDistribution.get(0).getAmount() + localDistribution.get(1).getAmount() + localDistribution.get(2).getAmount()));
        localTotal.add(new DataPointVo("华北地区", localDistribution.get(3).getAmount() + localDistribution.get(4).getAmount() + localDistribution.get(5).getAmount() + localDistribution.get(6).getAmount()));
        localTotal.add(new DataPointVo("华东地区", localDistribution.get(8).getAmount() + localDistribution.get(9).getAmount() + localDistribution.get(10).getAmount() + localDistribution.get(11).getAmount() + localDistribution.get(12).getAmount() + localDistribution.get(13).getAmount() + localDistribution.get(14).getAmount() + localDistribution.get(15).getAmount()));
        localTotal.add(new DataPointVo("华南地区", localDistribution.get(16).getAmount() + localDistribution.get(17).getAmount() + localDistribution.get(18).getAmount() + localDistribution.get(19).getAmount() + localDistribution.get(20).getAmount()));
        localTotal.add(new DataPointVo("西北地区", localDistribution.get(21).getAmount() + localDistribution.get(22).getAmount() + localDistribution.get(23).getAmount() + localDistribution.get(24).getAmount() + localDistribution.get(25).getAmount()));
        localTotal.add(new DataPointVo("东北地区", localDistribution.get(26).getAmount() + localDistribution.get(27).getAmount() + localDistribution.get(28).getAmount()));
        localTotal.add(new DataPointVo("西南地区", localDistribution.get(29).getAmount() + localDistribution.get(30).getAmount() + localDistribution.get(31).getAmount() + localDistribution.get(32).getAmount() + localDistribution.get(3).getAmount()));

        analysisDistributionVo.setIndustryDistribution(industryDistribution);
        analysisDistributionVo.setAgeDistribution(ageDistribution);
        analysisDistributionVo.setGenderDistribution(genderDistribution);
        analysisDistributionVo.setLocalDistribution(localDistribution);
        analysisDistributionVo.setLocalTotal(localTotal);


        return analysisDistributionVo;

    }

//---------------------------------------------------------------------------------------------------------

    /**
     * 新增、活跃用户、次日留存率
     *
     * @param sd   开始时间
     * @param ed   结束时间
     * @param type 101 新增 102 活跃用户 103 次日留存率
     * @return
     */
    public AnalysisUsersVo queryAnalysisUsersVo(Long sd, Long ed, Integer type) {
        //当前的开始,结束时间
        DateTime startTime = DateUtil.date(sd);//当前的开始时间
        DateTime endTime = DateUtil.date(ed);//当前的结束时间
          /*DateTime startTime = DateUtil.parse(sd);
        DateTime endTime = DateUtil.parse(ed);*/

        //去年的开始,结束时间
        DateTime lastStartTime = DateUtil.offsetMonth(startTime, -12);//一年前的开始时间
        DateTime lastEndTime = DateUtil.offsetMonth(endTime, -12);//一年前的结束时间

        AnalysisUsersVo analysisAnalysisUsersVo = new AnalysisUsersVo();

        switch (type) {
            //新增用户
            case 101:
                analysisAnalysisUsersVo = getAddingUserData(startTime, endTime, lastStartTime, lastEndTime);
                break;
            //活跃用户
            case 102:
                analysisAnalysisUsersVo = getActiveUser(startTime, endTime, lastStartTime, lastEndTime);
                break;
            //次日留存率
            case 103:
                //analysisAnalysisUsersVo = getNextDayRetention(startTime, endTime, lastStartTime, lastEndTime);
                break;

            default:
                return null;
        }

        return analysisAnalysisUsersVo;
    }

    /**
     * 次日留存率
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    /*private AnalysisUsersVo getNextDayRetention(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo usersVo = new AnalysisUsersVo();

        //时间戳之间的日志表数据
        //List<Log> managelogsList = this.dashboardApi.getManagelogsList(startTime.getTime(), endTime.getTime());

        //相差的天数
        Integer day = Convert.toInt(DateUtil.between(startTime, endTime, DateUnit.DAY));

        //时间戳之间的用户注册数据
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("created", startTime, endTime);
        List<User> userList = this.userMapper.selectList(wrapper);

        //今年的数据
        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= day + 1; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (int j = 0; j < userList.size(); j++) {
                User user = userList.get(j);
                String format = DateUtil.format(startTime, "yyyy-MM-dd");
                String userFormat = DateUtil.format(user.getCreated(), "yyyy-MM-dd");
                if (StrUtil.equals(format, userFormat)) {
                    //次日留存率,时间要往后推一天
                    Date nextDay = DateUtil.offsetDay(user.getCreated(), 1);
                    //一天的开始
                    Date beginOfDay = DateUtil.beginOfDay(nextDay);
                    //一天的结束
                    Date endOfDay = DateUtil.endOfDay(nextDay);
                    //查询第二天的日志表
                    //List<Log> managelogsList = this.dashboardApi.getManagelogsList(beginOfDay.getTime(), endOfDay.getTime());
                    Log managelogsByUserId = this.dashboardApi.getManagelogsByUserId(beginOfDay.getTime(), endOfDay.getTime(), user.getId());

                    QueryWrapper<Log> wrapper = new QueryWrapper<>();
                    wrapper.between("log_time", startTime.getTime(), endTime.getTime());
                    List<Log> managelogsList = this.logMapper.selectList(wrapper);

                    if (ObjectUtil.isNotEmpty(managelogsByUserId)) {
                        amount++;
                        continue;
                    }

                    *//*if(managelogsList.contains(user.getId())){
                        amount++;
                        //userList.remove(j);

                    }*//*
                }
            }
            String format = DateUtil.format(startTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            thisYear.add(dateNumberVo);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        usersVo.setThisYear(thisYear);

        //时间戳之间的用户注册数据
        QueryWrapper<User> lastWrapper = new QueryWrapper<>();
        lastWrapper.between("created", lastStartTime, lastEndTime);
        List<User> lastUserList = this.userMapper.selectList(lastWrapper);

        //去年的数据
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= day + 1; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (int j = 0; j < lastUserList.size(); j++) {
                User user = lastUserList.get(j);
                String format = DateUtil.format(lastStartTime, "yyyy-MM-dd");
                String userFormat = DateUtil.format(user.getCreated(), "yyyy-MM-dd");
                if (StrUtil.equals(format, userFormat)) {
                    //次日留存率,时间要往后推一天
                    Date nextDay = DateUtil.offsetDay(user.getCreated(), 1);
                    //一天的开始
                    Date beginOfDay = DateUtil.beginOfDay(nextDay);
                    //一天的结束
                    Date endOfDay = DateUtil.endOfDay(nextDay);
                    //查询第二天的日志表
                    //List<Log> managelogsList = this.dashboardApi.getManagelogsList(beginOfDay.getTime(), endOfDay.getTime());
                    Log managelogsByUserId = this.dashboardApi.getManagelogsByUserId(beginOfDay.getTime(), endOfDay.getTime(), user.getId());

                    if (ObjectUtil.isNotEmpty(managelogsByUserId)) {
                        amount++;
                        continue;
                    }
                }
            }
            String format = DateUtil.format(lastStartTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            lastYear.add(dateNumberVo);
            lastStartTime = DateUtil.offsetDay(lastStartTime, 1);
        }
        usersVo.setLastYear(lastYear);

        return usersVo;
    }*/
//------------------------------------------------------------------------------------------------------
    
    
    private AnalysisUsersVo getAddingUserData(DateTime startTime, DateTime endTime, DateTime lastStartTime, DateTime lastEndTime) {
        //相差一个月，31天
        long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
        //当前时间
        String today = DateUtil.today();
        //获取结束时间
        String format = DateUtil.format(endTime, "yyyy-MM-dd");
        if (betweenDay == 7 && StrUtil.equals(today, format)) {
            return this.getWeek(startTime, endTime, lastStartTime, lastEndTime);
        } else if (betweenDay == 30 && StrUtil.equals(today, format)) {
            return this.getMonth(startTime, endTime, lastStartTime, lastEndTime);
        } else {
            return this.getCustomTime(startTime, endTime, lastStartTime, lastEndTime);
        }
    }


/**
     * 本周新增用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    public AnalysisUsersVo getWeek(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo analysisUsersVo = new AnalysisUsersVo();

        //今年新增用户数据
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("created", startTime, endTime);
        List<User> userList = this.userMapper.selectList(wrapper);

        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : userList) {

                String dd1 = DateUtil.format(user.getCreated(), "dd");
                String dd2 = DateUtil.format(startTime, "dd");
                if (StrUtil.equals(dd1,dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(startTime, "MM-dd");
            dataPointVo.setTitle(format);
            dataPointVo.setAmount(amount);
            thisYear.add(dataPointVo);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        analysisUsersVo.setThisYear(thisYear);

        //去年新增用户数据
        QueryWrapper<User> lastWrapper = new QueryWrapper<>();
        lastWrapper.between("created", lastStartTime, lastEndTime);
        List<User> lastUserList = this.userMapper.selectList(lastWrapper);

        //按照一周7天遍历查询,如果日期和User创建日期相同 amount+1
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : lastUserList) {

                String dd1 = DateUtil.format(user.getCreated(), "dd");
                String dd2 = DateUtil.format(lastStartTime, "dd");
                if (StrUtil.equals(dd1,dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(lastStartTime, "MM-dd");
            dataPointVo.setTitle(format);
            dataPointVo.setAmount(amount);
            lastYear.add(dataPointVo);
            lastStartTime = DateUtil.offsetDay(lastStartTime, 1);
        }
        analysisUsersVo.setLastYear(lastYear);

        return analysisUsersVo;
    }

    /**
     * 本月新增用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    public AnalysisUsersVo getMonth(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo analysisAnalysisUsersVo = new AnalysisUsersVo();

        //今年新增用户数据
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("created", startTime, endTime);
        List<User> userList = this.userMapper.selectList(wrapper);

        //按照一月30天遍历查询,如果月份日期和User创建的月份日期相同 amount+1
        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= 31; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : userList) {
                String dd1 = DateUtil.format(user.getCreated(), "MM-dd");
                String dd2 = DateUtil.format(startTime, "MM-dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(startTime, "MM-dd");
            dataPointVo.setTitle(format);
            dataPointVo.setAmount(amount);
            thisYear.add(dataPointVo);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        analysisAnalysisUsersVo.setThisYear(thisYear);

        //去年新增用户数据
        QueryWrapper<User> lastWrapper = new QueryWrapper<>();
        lastWrapper.between("created", lastStartTime, lastEndTime);
        List<User> lastUserList = this.userMapper.selectList(lastWrapper);
        //按照一月30天遍历查询,如果月份日期和User创建的月份日期相同 amount+1
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 31; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : lastUserList) {
                String dd1 = DateUtil.format(user.getCreated(), "MM-dd");
                String dd2 = DateUtil.format(lastStartTime, "MM-dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(lastStartTime, "MM-dd");
            dataPointVo.setTitle(format);
            dataPointVo.setAmount(amount);
            lastYear.add(dataPointVo);
            lastStartTime = DateUtil.offsetDay(lastStartTime, 1);
        }
        analysisAnalysisUsersVo.setLastYear(lastYear);

        return analysisAnalysisUsersVo;
    }
    /**
     * 自定义新增用户数据
     *
     * @param      //当前的开始时间
     * @param        //当前的结束时间
     * @param  //一年前的开始时间
     * @param    //一年前的开始时间
     * @return
     */
    private AnalysisUsersVo getCustomTime(DateTime startTime, DateTime endTime, DateTime lastStartTime, DateTime lastEndTime) {
        AnalysisUsersVo analysisUsersVo = new AnalysisUsersVo();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("created", startTime, endTime);
        List<User> userList = this.userMapper.selectList(wrapper);

        ArrayList<DataPointVo> thisYear = new ArrayList<>();

        for (int i = 1; i <= 12; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : userList) {
                int month = DateUtil.month(user.getCreated()) + 1;
                if (i == month) {
                    amount++;
                }
            }
            dataPointVo.setTitle(i + "月");
            dataPointVo.setAmount(amount);
            thisYear.add(dataPointVo);
        }
        analysisUsersVo.setThisYear(thisYear);

        //去年新增数据
        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
        wrapper2.between("created", lastStartTime, lastEndTime);
        List<User> lastUserList = this.userMapper.selectList(wrapper2);
        ArrayList<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            DataPointVo dataPointVo = new DataPointVo();
            Integer amount = 0;
            for (User user : lastUserList) {
                int month = DateUtil.month(user.getCreated()) + 1;
                if (i == month) {
                    amount++;
                }
            }
            dataPointVo.setTitle(i + "月");
            dataPointVo.setAmount(amount);
            lastYear.add(dataPointVo);
        }

        analysisUsersVo.setLastYear(lastYear);
        return analysisUsersVo;
    }
//--------------------------------------------------------------------------------------------------------
    /**
     * 活跃用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    private AnalysisUsersVo getActiveUser(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //相差一个月，31天
        long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
        //当前时间
        String today = DateUtil.today();
        //获取结束时间
        String format = DateUtil.format(endTime, "yyyy-MM-dd");
        if (betweenDay == 7 && StrUtil.equals(today, format)) {
            return this.getActiveUserWeek(startTime, endTime, lastStartTime, lastEndTime);
        } else if (betweenDay == 30 && StrUtil.equals(today, format)) {
            return this.getActiveUserMonth(startTime, endTime, lastStartTime, lastEndTime);
        } else {
            return this.getActiveUserCustomTime(startTime, endTime, lastStartTime, lastEndTime);
        }
    }

    /**
     * 本周活跃用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    private AnalysisUsersVo getActiveUserWeek(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo usersVo = new AnalysisUsersVo();

        //今年新增用户数据
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.between("log_time", startTime.getTime(), endTime.getTime());
        List<Log> managelogsList = this.logMapper.selectList(wrapper);

        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= 8; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (Log managelogs : managelogsList) {
                String dd1 = DateUtil.format(DateUtil.date(managelogs.getLogTime()), "dd");
                String dd2 = DateUtil.format(startTime, "dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(startTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            thisYear.add(dateNumberVo);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        usersVo.setThisYear(thisYear);

        //去年新增用户数据
        QueryWrapper<Log> wrapper1 = new QueryWrapper<>();
        wrapper1.between("log_time", lastStartTime.getTime(), lastEndTime.getTime());
        List<Log> lastManagelogsList = this.logMapper.selectList(wrapper1);

        //按照一周7天遍历查询,如果日期和User创建日期相同 amount+1
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 8; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;

            for (Log managelogs : lastManagelogsList) {
                String dd1 = DateUtil.format(DateUtil.date(managelogs.getLogTime()), "dd");
                String dd2 = DateUtil.format(lastStartTime, "dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(lastStartTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            lastYear.add(dateNumberVo);
            lastStartTime = DateUtil.offsetDay(lastStartTime, 1);
        }
        usersVo.setLastYear(lastYear);

        return usersVo;
    }

    /**
     * 本月活跃用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    private AnalysisUsersVo getActiveUserMonth(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo usersVo = new AnalysisUsersVo();

        //今年新增用户数据
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.between("log_time", startTime.getTime(), endTime.getTime());
        List<Log> managelogsList = this.logMapper.selectList(wrapper);

        //按照一月30天遍历查询,如果月份日期和User创建的月份日期相同 amount+1
        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= 31; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (Log managelogs : managelogsList) {
                String dd1 = DateUtil.format(DateUtil.date(managelogs.getLogTime()), "MM-dd");
                String dd2 = DateUtil.format(startTime, "MM-dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(startTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            thisYear.add(dateNumberVo);
            startTime = DateUtil.offsetDay(startTime, 1);
        }
        usersVo.setThisYear(thisYear);

        //去年新增用户数据
        QueryWrapper<Log> wrapper1 = new QueryWrapper<>();
        wrapper1.between("log_time", lastStartTime.getTime(), lastEndTime.getTime());
        List<Log> lastManagelogsList = this.logMapper.selectList(wrapper1);


        //按照一月30天遍历查询,如果月份日期和User创建的月份日期相同 amount+1
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 31; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (Log managelogs : lastManagelogsList) {
                String dd1 = DateUtil.format(DateUtil.date(managelogs.getLogTime()), "MM-dd");
                String dd2 = DateUtil.format(lastStartTime, "MM-dd");
                if (StrUtil.equals(dd1, dd2)) {
                    amount++;
                }
            }
            String format = DateUtil.format(lastStartTime, "MM-dd");
            dateNumberVo.setTitle(format);
            dateNumberVo.setAmount(amount);
            lastYear.add(dateNumberVo);
            lastStartTime = DateUtil.offsetDay(lastStartTime, 1);
        }
        usersVo.setLastYear(lastYear);

        return usersVo;
    }

    /**
     * 自定义时间活跃用户数据
     *
     * @param startTime     //当前的开始时间
     * @param endTime       //当前的结束时间
     * @param lastStartTime //一年前的开始时间
     * @param lastEndTime   //一年前的开始时间
     * @return
     */
    private AnalysisUsersVo getActiveUserCustomTime(Date startTime, Date endTime, Date lastStartTime, Date lastEndTime) {
        //创建返回对象
        AnalysisUsersVo usersVo = new AnalysisUsersVo();

        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.between("log_time", startTime.getTime(), endTime.getTime());
        List<Log> managelogsList = this.logMapper.selectList(wrapper);

        List<DataPointVo> thisYear = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (Log managelogs : managelogsList) {
                //获得月份，从0开始计数 所以需要+1
                int month = DateUtil.month(DateUtil.date(managelogs.getLogTime())) + 1;
                if (i == month) {
                    amount++;
                }
            }
            dateNumberVo.setTitle(i + "月");
            dateNumberVo.setAmount(amount);
            thisYear.add(dateNumberVo);
        }
        usersVo.setThisYear(thisYear);

        QueryWrapper<Log> wrapper1 = new QueryWrapper<>();
        wrapper1.between("log_time", lastStartTime.getTime(), lastEndTime.getTime());
        List<Log> lastManagelogsList = this.logMapper.selectList(wrapper1);

        //按照一年12个月遍历查询,如果月份和User创建月份相同 amount+1
        List<DataPointVo> lastYear = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            DataPointVo dateNumberVo = new DataPointVo();
            Integer amount = 0;
            for (Log managelogs : lastManagelogsList) {
                //获得月份，从0开始计数 所以需要+1
                int month = DateUtil.month(DateUtil.date(managelogs.getLogTime())) + 1;
                if (i == month) {
                    amount++;
                }
            }
            dateNumberVo.setTitle(i + "月");
            dateNumberVo.setAmount(amount);
            lastYear.add(dateNumberVo);
        }
        usersVo.setLastYear(lastYear);

        return usersVo;
    }
//--------------------------------------------------------------------------------------------------------





    //概要统计信息
    public AnalysisSummaryVo getSummary() {
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();
        DateTime date = DateUtil.date(System.currentTimeMillis());
        DateTime todayTime = DateUtil.beginOfDay(date);//当天00:00:00
        //1.累计用户
        analysisSummaryVo.setCumulativeUsers(userMapper.selectCount(new QueryWrapper<>()));
        //2.过去30天活跃用户
        DateTime passMonthTime = DateUtil.offsetDay(todayTime, -30);//过去30天时间

        analysisSummaryVo.setActivePassMonth(this.getActiveUsers(passMonthTime));

        //3.过去7天活跃用户
        DateTime passWeekTime = DateUtil.offsetDay(todayTime, -7);//过去7天时间

        analysisSummaryVo.setActivePassWeek(this.getActiveUsers(passWeekTime));
        //4.今日新增用户
        QueryWrapper<User> todayWrapper = new QueryWrapper<>();
        todayWrapper.ge("created", todayTime);
        Integer todayNewCount = userMapper.selectCount(todayWrapper);//当天用户新增数量
        analysisSummaryVo.setNewUsersToday(todayNewCount);
        //5.今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        DateTime lastTime = DateUtil.offsetDay(todayTime, -1);//昨天时间
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.ge("created", lastTime).lt("created", todayTime);
        Integer count = userMapper.selectCount(wrapper);//前一天用户新增数量
        //计算涨跌率
        analysisSummaryVo.setNewUsersTodayRate(ratio(todayNewCount,count));

        //6.今日登录次数
        QueryWrapper<Log> todayLoginWrapper = new QueryWrapper<>();
        todayLoginWrapper.ge("log_time",todayTime.toJdkDate().getTime());
        List<Log> todayUsers = logMapper.selectList(todayLoginWrapper);//当天登录用户

        analysisSummaryVo.setLoginTimesToday(todayUsers.size());
        //7.今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        QueryWrapper<Log> loginWrapper = new QueryWrapper<>();
        loginWrapper.ge("log_time", lastTime.toJdkDate().getTime()).lt("log_time", todayTime.toJdkDate().getTime());
        List<Log> lastUsers = logMapper.selectList(loginWrapper);//前一天登录用户

        analysisSummaryVo.setLoginTimesTodayRate(ratio(todayUsers.size(),lastUsers.size()));
        //8.今日活跃用户
        HashSet<Long> todayLogs = new HashSet<>();
        for (Log todayUser : todayUsers) {
            todayLogs.add(todayUser.getId());
        }
        analysisSummaryVo.setActiveUsersToday(todayLogs.size());
        //9.今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        HashSet<Long> lastLogs = new HashSet<>();
        for (Log lastUser : lastUsers) {
            lastLogs.add(lastUser.getId());
        }
        analysisSummaryVo.setActiveUsersTodayRate(ratio(todayLogs.size(),lastLogs.size()));
        //10.过去7天平均日使用时长，单位秒
        analysisSummaryVo.setUseTimePassWeek(28800);
        //11.昨日活跃用户
        analysisSummaryVo.setActiveUsersYesterday(lastLogs.size());
        //12.昨日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        DateTime beforTime = DateUtil.offsetDay(todayTime, -2);//前天时间
        Integer beforCount = getActiveUsersByTime(beforTime, lastTime);
        analysisSummaryVo.setActiveUsersYesterdayRate(ratio(lastLogs.size(),beforCount));
        return analysisSummaryVo;
    }

    /**
     * 查询活跃用户
     * @param dateTime
     * @return
     */
    private Integer getActiveUsers(DateTime dateTime){
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.ge("log_time",dateTime.toJdkDate().getTime());
        List<Log> users = logMapper.selectList(wrapper);
        HashSet<Long> logs = new HashSet<>();
        for (Log user : users) {
            logs.add(user.getId());
        }
        return logs.size();
    }

    /**
     *
     * 查询时间段内活跃用户
     * @param start
     * @param end
     * @return
     */
    private Integer getActiveUsersByTime(DateTime start,DateTime end){
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.ge("log_time",start.toJdkDate().getTime()).lt("log_time",end.toJdkDate().getTime());
        List<Log> users = logMapper.selectList(wrapper);
        HashSet<Long> logs = new HashSet<>();
        for (Log user : users) {
            logs.add(user.getId());
        }
        return logs.size();
    }


    /**
     * 计算涨跌率:涨跌幅＝涨跌值／昨收盘＊100％
     *
     * @param newUsersToday  今日新增人数
     * @param lastUsersToday 昨日新增人数
     * @return
     */
    private Integer ratio(Integer newUsersToday, Integer lastUsersToday) {
        if (newUsersToday == 0 && lastUsersToday == 0) {
            return 0;
        } else if (newUsersToday == 0) {
            return -(lastUsersToday * 100);
        } else if (lastUsersToday == 0) {
            return newUsersToday * 100;
        } else {
            return ((newUsersToday - lastUsersToday) / lastUsersToday * 100);
        }
    }


}
